package com.lkn.socket.inetaddress;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
/**
 * 获取主机和地址
 * @author albert
 *
 */
public class InetAddressTest {
	public static void main(String[] args) {
		try {
			//获取主机的网络接口列表
			Enumeration<NetworkInterface> interfaceList = NetworkInterface.getNetworkInterfaces();
			//空列表检测
			if(interfaceList==null){
				System.out.println("找不到interface！");
			}else{
				//获取并打印每一个接口的地址
				while (interfaceList.hasMoreElements()) {
					NetworkInterface iface = (NetworkInterface) interfaceList.nextElement();
					//打印接口名
					System.out.println("Interface "+iface.getName()+":");
					//获取与接口相关联的地址
					Enumeration<InetAddress> addList = iface.getInetAddresses();
					//空列表检测
					if(!addList.hasMoreElements()){
						System.out.println("\t No Address for this Interface了");
					}
					//迭代列表，打印出每一个地址
					while (addList.hasMoreElements()) {
						InetAddress inetAddress = (InetAddress) addList.nextElement();
						System.out.print("Address is "+((inetAddress instanceof Inet4Address ? "(v4)":(inetAddress instanceof Inet6Address ? "(v6)" : "(?)"))));
						System.out.println(":"+inetAddress.getHostAddress());
					}
				}
			}
			//异常捕获
		} catch (SocketException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			System.out.println("出错啦！"+e.getMessage());
		}
		//获取从命令行输入的每一个参数所对应的主机名和地址
		for(String host: args){
			System.out.println(host+":");
			try {
				//获取给定主机名/地址的相关地址列表
				InetAddress[]addressList = InetAddress.getAllByName(host);
				//迭代输出
				for(InetAddress address:addressList){
					System.out.println(""+address.getHostName()+"/"+address.getHostAddress());
				}
				//异常捕获
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
//				e.printStackTrace();
				System.out.println("未知的host:"+host);
			}
			
		}
	}
}
